package models;

import play.*;
import play.data.validation.Email;
import play.data.validation.Password;
import play.data.validation.Required;
import play.db.jpa.*;
import play.libs.Codec;

import javax.persistence.*;

import java.util.*;

@Entity
public class Customer extends Model {
	@Email
	@Required
	public String email;

	@Required
	public String name;

	@Required
	public String passwordHash;
	
	// public String address;
	// public String telephone;

	public String getPasswordHash() {
		return passwordHash;
	}

	public void setPasswordHash(String passwordHash) {
		this.passwordHash = passwordHash;
	}

	public String needConfirmation;

	@OneToMany
	public List<ShoppingOrder> orders = new LinkedList<ShoppingOrder>();

	public Customer(String email, String password, String name) {
		this.email = email;
		this.passwordHash = Codec.hexMD5(password);
		this.name = name;
		this.needConfirmation = Codec.UUID();
		create();
	}

	public boolean checkPassword(String password) {
		return passwordHash.equals(Codec.hexMD5(password));
	}

	@Override
	public String toString() {
		return "Customer [emailID=" + email + ", name=" + name + ", password="
				+ passwordHash + ", orders=" + orders + "]";
	}

	public static Customer findByEmail(String email) {
		return find("email", email).first();
	}

	public static Customer findByRegistrationUUID(String uuid) {
		return find("needConfirmation", uuid).first();
	}

	public static List<Customer> findAll(int page, int pageSize) {
		return Customer.all().fetch(page, pageSize);
	}

	public static boolean isEmailAvailable(String email) {
		return findByEmail(email) == null;
	}

}
